<template>
  <!-- 报表工具 -->
  <div class="report">

    <div class="report_title df jc-sb ai-c">
      <div class="df ai-c ">
        <div class="df ai-c"><span>当前月份： </span>
          <el-date-picker v-model="searchMonth" type="month" placeholder="请选择" @change="search_change" :format="'YYYY-MM'" value-format="YYYY-MM" :disabled-date="disabledDate" />
        </div>
        <div class="df ai-c"><span>姓名： </span><el-input v-model="searchName" type="text" placeholder="请输入" @change="search_change"></el-input></div>
      </div>
      <div>
        <lay-button class="btn_search" size="sm" @click="search_change">查询</lay-button>
        <lay-button class="btn_resert" size="sm" @click="resert">重置</lay-button>
      </div>
    </div>
    <div style="padding: 8px 0;box-sizing: border-box;">
      <lay-button size="sm" v-permissions="'reportTools_push'" v-show="btn_name!='导出'" @click="createReport">{{btn_name}}</lay-button>
      <lay-button size="sm" v-permissions="'reportTools_export'" v-show="btn_name=='导出' ||btn_name=='信息推送' " @click="exprotReport">导出</lay-button>
    </div>
    <div class="report_content">
      <el-scrollbar>
        <lay-table :columns="columns7" :data-source="dataSource7" :default-toolbar="false">
          <template v-slot:operator="{ row }">
            <el-tag type="success" v-if="row.status=='1'"> 已确认 </el-tag>
            <el-tag type="danger" v-else> 等待确认 </el-tag>

            <!-- <el-button link :type="row.status =='1'? 'danger':'primary'  "> {{ row.status =='1'?"已确认":'等待确认' }} </el-button> -->
          </template>
        </lay-table>
      </el-scrollbar>

      <!-- <el-table :data="dataSource7" border style="width: 100%" :span-method="spanMethod7">
        <el-table-column v-for="(item, index) in columns7" :key="index" :prop="item.key" :label="item.title"></el-table-column>
        <el-table-column prop="" label="操作" width="">
          <template #default="scope">
            <div>
              <el-button link :type="scope.row.status =='1'? 'danger':'primary'  "> {{ scope.row.status =='1'?"已确认":'等待确认' }} </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table> -->

      <!-- <el-scrollbar ref="scrollbarRef" @scroll="scroll">
        <div ref="innerRef">
          <table ref="tableRef" class="report_table" border>
            <tbody>
              <tr>
                <td rowspan="2" colspan="4">单点评吸汇总</td>
                <td rowspan="3">缺席日期</td>
                <td :colspan="allInfo?.dayHeads?.length">日评吸明细</td>
                <td :colspan="allInfo?.weekHeads?.length">周评吸明细</td>
                <td :colspan="allInfo?.monthHeads?.length">单点评吸明细</td>
                <td :colspan="allInfo?.otherHeads?.length">其他评吸明细</td>
              </tr>
              <tr>

                <td v-for="(item,index) in allInfo.dayHeads" :key="index">{{item[0]}}</td>
                <td v-for="(item,index) in allInfo.weekHeads" :key="index">{{item[0]}}</td>
                <td rowspan="2" v-for="(item, index) in allInfo.monthHeads" :key="index">{{item}}</td>
                <td rowspan="2" v-for="(item, index) in allInfo.otherHeads" :key="index">{{item}}</td>

              </tr>

              <tr>
                <td v-for="(item,index) in allInfo.monthCollectHeads" :key="index">
                  {{item}}
                </td>
                <td v-for="(item,index) in allInfo.dayHeads" :key="index">{{item[1]}}</td>
                <td v-for="(item,index) in allInfo.weekHeads" :key="index">{{item[1]}}</td>
              </tr>

              <tr v-for="(item,index) in allInfo?.allPeopleDetail" :key="index">
                <td>{{item.serialNo}}</td>
                <td>{{item.name}}</td>
                <td>{{item.unitNum}}</td>
                <td>{{item.productNum}}</td>
                <td></td>
                <td></td>
                <td v-for="(dayItem,dayIndex) in item.daysNum" :key="dayIndex">{{dayItem}}</td>
                <td></td>
                <td v-for="(weekItem,weekIndex) in item.weeksNum" :key="weekIndex">{{weekItem}}</td>
                <td v-for="(monthItem,monthIndex) in item.monthNum" :key="monthIndex">{{monthItem}}</td>
                <td v-for="(otherItem,otherIndex) in item.otherNum" :key="otherIndex">{{otherItem}}</td>

              </tr>

            </tbody>
          </table>
        </div>

      </el-scrollbar>

      <el-slider v-if="max>0" v-model="sliderValue" :max="max" :format-tooltip="formatTooltip" @input="inputSlider" /> -->

    </div>
  </div>
</template>  

<script setup lang="ts">
import http from "@/http/index";
import { ref, onMounted, nextTick } from "vue";
import { layer } from "@layui/layer-vue";

const max = ref(0);
const sliderValue = ref(0);
const innerRef = ref();
const scrollbarRef = ref();
const tableRef = ref();

// 禁止选择的逻辑
const disabledDate = (time) => {
  let flag = true;
  try {
    // console.log(time);

    // 获取当前日期
    const now = new Date();
    // 将当前日期的日设置为1日，并且清除小时等信息，以便仅比较年月
    now.setDate(1);
    now.setHours(0, 0, 0, 0);

    // 同理，清除参数时间的日以下的部分
    const incomingDate = new Date(time);
    incomingDate.setDate(1);
    incomingDate.setHours(0, 0, 0, 0);

    flag = incomingDate >= now;

    // 如果参数时间大于等于当前时间，则禁止选择
  } catch (err) {
    console.log(err);
  }

  return flag;
};

// onMounted(() => {
//   console.log(innerRef.value.clientWidth);

//   setTimeout(() => {
//     console.log(tableRef.value.clientWidth);
//     max.value = tableRef.value.clientWidth || 0;
//   }, 100);

//   // max.value = innerRef.value!.clientHeight - 380
// });

// const inputSlider = (value: number) => {
//   console.log(value);

//   // scrollbarRef.value!.setScrollTop(value)
//   scrollbarRef.value!.setScrollLeft(value)
// };
// const scroll = ({ scrollTop, scrollLeft }) => {
//   console.log(scrollTop,scrollLeft);

//   sliderValue.value = scrollLeft
// };
// const formatTooltip = (value: number) => {
//   console.log(value);

//   return `${value} px`
// };

// 月份
const searchMonth = ref("");

function time(t) {
  var dt = new Date(t);
  var y = dt.getFullYear();
  var m = dt.getMonth();
  m = m < 10 ? "0" + m : m;

  return `${y}-${m}`;
}

// 姓名
const searchName = ref("");

const columns7 = [
  {
    title: "所属部门",
    key: "orgName",
  },
  {
    title: "姓名",
    key: "userName",
  },
  // {
  //   title: "身份证号",
  //   key: "identityCard",
  // },
  {
    title: "单料烟支数（月）",
    key: "unblendedAmount",
  },
  {
    title: "成品烟支数（月）",
    key: "perfectAmout",
  },

  // {
  //   title: "日评吸（支）",
  //   key: "taskDay",
  // },
  // {
  //   title: "周评吸（支）",
  //   key: "taskWeek",
  // },
  {
    title: "总金额（元）",
    key: "totalAmount",
  },
  {
    title: "部门合计（元）",
    key: "orgMoney",
  },
  {
    title: "状态",
    customSlot: "operator",
    key: "operator",
  },
];

const dataSource7 = ref();

const spanMethod7 = ({ row, column, rowIndex, columnIndex }) => {
  if (columnIndex === 0) {
    // if (rowIndex % 2 === 0) {
    //   return {
    //     rowspan: 2,
    //     colspan: 1,
    //   };
    // } else {
    //   return {
    //     rowspan: 0,
    //     colspan: 0,
    //   };
    // }
  }

  // if (columnIndex === 0) {

  //   // //  如果是第一列 或者是第五列的话
  //   // console.log(column);
  //   // if (rowIndex === 0) {
  //   //   return [2, 1]; // [2,3] 合并两行三列
  //   // } else if (rowIndex < 2) {
  //   //   return [0, 0];
  //   // }
  //   // if (rowIndex === 2) {
  //   //   return [5, 1];
  //   // } else if (rowIndex < 7) {
  //   //   return [0, 0];
  //   // }
  // } else {
  //   // return [0,0]
  // }

  //   if (columnIndex === 0) {
  //     return {
  //       rowspan: 3,
  //       colspan: 1,
  //     };
  //   }
  //   const rule = mergeRules.value.find((r) => r.column === columnIndex);
  //   if (rule) {
  //     if (rowIndex === 0 || rowIndex === rule.rowsToMerge) {
  //       // 开始新的合并或结束当前合并
  //       currentMerge.value = { column: rule.column, count: 0 };
  //     }
  //     if (currentMerge.value.column === rule.column) {
  //       currentMerge.value.count++;
  //       if (currentMerge.value.count <= rule.rowsToMerge) {
  //         // 在合并的范围内
  //         return {
  //           rowspan: rule.rowsToMerge,
  //           colspan: 1,
  //         };
  //       } else {
  //         // 超出合并范围，隐藏单元格
  //         return {
  //           rowspan: 0,
  //           colspan: 0,
  //         };
  //       }
  //     }
  //   }
};

const search_change = async (e) => {
  console.log(e);
  await get_list();
};
const resert = async () => {
  searchMonth.value = "";
  searchName.value = "";
  await get_list();
};

// 按钮文字
const btn_name = ref("");
// 生成报表
const createReport = async () => {
  if (btn_name.value === "生成津贴") {
    const res = await http.corsApi("/report/creat", "get", {
      date: searchMonth.value,
    });
    console.log(res);
    if (res.code == 200) {
      layer.msg("生成成功", { icon: 1 });
      await get_list();
    }
  } else if (btn_name.value === "信息推送") {
    const res = await http.corsApi(`/report/pushReport?date=${searchMonth.value}`, "get", {});
    console.log(res);
    if (res.code == 200) {
      layer.msg("推送成功", { icon: 1 });

      await get_list();
    }
  } else if (btn_name.value === "导出") {
    const res = await http.corsApi("/report/downloadNonOfficeExcel", "get", {}, { is_msg: false, formData: true });
    console.log(res);
    if (res.data) {
      // res 为后端返回的响应对象
      let blob = new Blob([res.data]);
      let url = window.URL.createObjectURL(res.data);
      let a = document.createElement("a");
      a.href = url;
      a.download = decodeURI(res.headers["content-disposition"]).split("filename=")[1].replace(/"/g, "") || new Date().getTime() + ".xls";
      a.click();
      window.URL.revokeObjectURL(url);
      layer.msg("导出成功", { icon: 1, time: 2000 });

      console.log(decodeURI(res.headers["content-disposition"]).split("filename=")[1].replace(/"/g, ""));
    }
  }
};
 
const exprotReport = async () => {
  const res = await http.corsApi(`/report/downloadNonOfficeExcel?date=${searchMonth.value}`, "get", {}, { is_msg: false, formData: true });
  console.log(res);
  if (res.data) {
    // res 为后端返回的响应对象
    let blob = new Blob([res.data]);
    let url = window.URL.createObjectURL(res.data);
    let a = document.createElement("a");
    a.href = url;
    a.download = decodeURI(res.headers["content-disposition"]).split("filename=")[1].replace(/"/g, "") || new Date().getTime() + ".xls";
    a.click();
    window.URL.revokeObjectURL(url);
    layer.msg("导出成功", { icon: 1, time: 2000 });

    console.log(decodeURI(res.headers["content-disposition"]).split("filename=")[1].replace(/"/g, ""));
  }
};

const get_list = async () => {
  const res = await http.corsApi("/report/queryReport", "get", {
    date: searchMonth.value,
    name: searchName.value,
  });
  console.log(res);

  if (!res.data.status) {
    btn_name.value = "生成津贴";
    dataSource7.value = [];
  } else {
    if (res.data.list && res.data.list.length > 0) {
      dataSource7.value = res.data.list;
      if (res.data.list.length && res.data.list[0].pushStatus == "0") {
        btn_name.value = "信息推送";
      } else {
        btn_name.value = "导出";
      }
    } else {
      console.log(111111);

      dataSource7.value = [];
    }
  }
};

const allInfo = ref([]);
// 获取大报表列表
const get_all_report_list = async () => {
  const res = await http.corsApi("/report/excelInfo", "get", {});
  console.log(res);
  allInfo.value = res.data;
};

onMounted(async () => {
  // get_all_report_list();

  searchMonth.value = time(new Date().getTime());

  await get_list();
});
</script> 

<style scoped lang="scss">
.report {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 20px;
  &_title {
    > div {
      span {
        width: 120px;
        text-align: right;
      }
    }
  }
  &_content {
  }
}

.report_table {
  min-width: 600px;
  td {
    padding: 6px 12px;
    white-space: nowrap;
    text-align: center;
  }
}
</style>